import React, { useImperativeHandle, forwardRef } from 'react'
import { Form, Input, Select } from 'antd'

function DataSourceForm(props, ref) {
  const { data, readOnly } = props;
  const { Option } = Select;

  const [form] = Form.useForm();
  useImperativeHandle(ref, () => ({
    // TODO: 请求发送
    getValue: () => {
      form.validateFields().then((values) => {
        console.log("values", values);
      })
    }
  }));

  function onChange(value) {
    console.log(`selected ${value}`);
  }

  function onSearch(val) {
    console.log('search:', val);
  }

  return (
    <Form layout="horizontal" form={form}>
      <Form.Item name='type' label="数据库类型" rules={[{ isRequired: true }]} >
        {readOnly && <Input defaultValue={data["type"]} readOnly={readOnly} />}
        {!readOnly &&
          <Select
            showSearch
            placeholder="选择一种数据库"
            optionFilterProp="children"
            onChange={onChange}
            onSearch={onSearch}
            filterOption={(input, option) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            defaultValue={data["type"]}
          >
            <Option value="MySQL">MySQL</Option>
            <Option value="SQL Server">SQL Server</Option>
            <Option value="Redis">Redis</Option>
          </Select>
        }
      </Form.Item>
      <Form.Item name='name' label="数据源名称" rules={[{ isRequired: true }]} >
        <Input defaultValue={data["name"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='note' label="数据源描述" rules={[{ isRequired: true }]} >
        <Input.TextArea defaultValue={data["note"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='driver' label="JDBC Driver Class" rules={[{ isRequired: true }]} >
        <Input defaultValue={data["driver"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='url' label="JDBC URL" rules={[{ isRequired: true }]} >
        <Input.TextArea defaultValue={data["url"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='username' label="用户名" rules={[{ isRequired: true }]} >
        <Input defaultValue={data["username"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='password' label="密码" rules={[{ isRequired: true }]} >
        <Input.Password defaultValue={data["password"]} readOnly={readOnly} />
      </Form.Item>
      <Form.Item name='tableSql' label="获取数据表的SQL" rules={[{ isRequired: true }]} >
        <Input.TextArea defaultValue={data["tableSql"]} readOnly={readOnly} placeholder='这段SQL会被用来执行获取数据表操作' />
      </Form.Item>

    </Form>
  )
}

export default forwardRef(DataSourceForm)